const { createApp } = Vue;

createApp({
    data() {
        return {
            searchQuery: '',
            selectedField: '',
            showAppointmentForm: false,
            selectedTherapist: null,
            selectedDate: '',
            selectedTime: '',
            availableDates: [],
            timeSlots: [
                '09:00-10:00',
                '10:00-11:00',
                '11:00-12:00',
                '14:00-15:00',
                '15:00-16:00',
                '16:00-17:00'
            ],
            fields: [
                '情绪管理',
                '婚恋关系',
                '职场压力',
                '家庭关系',
                '个人成长'
            ],
            therapists: [],
            loading: false,
            error: null,
            showDetailModal: false,
            selectedExperience: '',
            selectedRating: '',
            availableTimeSlots: [],
        };
    },
    computed: {
        filteredTherapists() {
            return this.therapists.filter(therapist => {
                const matchQuery = !this.searchQuery ||
                    therapist.name.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
                    therapist.title.toLowerCase().includes(this.searchQuery.toLowerCase());

                const matchField = !this.selectedField ||
                    therapist.fields.includes(this.selectedField);

                const matchExperience = !this.selectedExperience ||
                    this.checkExperienceMatch(therapist.experience, this.selectedExperience);

                const matchRating = !this.selectedRating ||
                    therapist.rating >= parseFloat(this.selectedRating);

                return matchQuery && matchField && matchExperience && matchRating;
            });
        }
    },
    methods: {
        goToPage(page) {
            switch (page) {
                case 'index':
                    window.location.href = 'index.html';
                    break;
                case 'consultation':
                    window.location.href = 'consultation.html';
                    break;
                case 'therapist':
                    window.location.href = 'therapist.html';
                    break;
                case 'about':
                    window.location.href = 'about.html';
                    break;
                case 'user-center':
                    window.location.href = 'user-center.html';
                    break;
                case 'login':
                    window.location.href = 'login.html';
                    break;
            }
        },
        showDetail(therapist) {
            this.selectedTherapist = therapist;
            this.showDetailModal = true;
        },
        makeAppointment(therapist) {
            this.selectedTherapist = therapist;
            this.selectedDate = '';
            this.selectedTime = '';
            this.availableTimeSlots = [];
            this.showAppointmentForm = true;

            // 生成今天和未来6天的日期
            const today = new Date();
            this.availableDates = [];

            for (let i = 0; i < 7; i++) {
                const date = new Date(today);
                date.setDate(today.getDate() + i);
                this.availableDates.push({
                    value: this.formatDate(date),
                    label: this.formatDateLabel(date)
                });
            }
        },
        formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },
        formatDateLabel(date) {
            const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            const isToday = date.getTime() === today.getTime();
            const weekday = weekdays[date.getDay()];
            return `${this.formatDate(date)} ${weekday}${isToday ? ' (今天)' : ''}`;
        },
        cancelAppointment() {
            this.showAppointmentForm = false;
            this.selectedTherapist = null;
            this.selectedDate = '';
            this.selectedTime = '';
        },
        async submitAppointment() {
            if (!this.selectedDate || !this.selectedTime) {
                alert('请选择预约日期和时间');
                return;
            }

            const appointmentData = {
                therapistPhone: this.selectedTherapist.phone,
                appointmentDate: this.selectedDate,
                appointmentTime: this.selectedTime,
                type: 'offline'
            };

            console.log('预约数据:', appointmentData); // 添加调试日志

            try {
                const token = localStorage.getItem('token');
                const response = await fetch('/api/appointments', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': token
                    },
                    body: JSON.stringify(appointmentData)
                });

                if (response.status === 401) {
                    localStorage.removeItem('token');
                    window.location.href = '/login.html';
                    return;
                }

                const data = await response.json();
                if (data.code === "200") {
                    alert('预约成功！');
                    this.cancelAppointment();
                } else {
                    throw new Error(data.message || '预约失败');
                }
            } catch (error) {
                console.error('预约失败:', error);
                alert('预约失败，请稍后重试');
            }
        },
        async fetchTherapists() {
            this.loading = true;
            this.error = null;
            try {
                const token = localStorage.getItem('token');
                if (!token) {
                    window.location.href = '/login.html';
                    return;
                }

                const response = await fetch('/api/therapists', {
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': token
                    }
                });

                if (response.status === 401) {
                    console.log('Token已失效，需要重新登录');
                    localStorage.removeItem('token');
                    window.location.href = '/login.html';
                    return;
                }

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();
                console.log('收到的原始数据:', data); // 调试日志

                if (data.code === "200") {
                    this.therapists = data.data.map(therapist => {
                        // 将字符串格式的fields转换为数组
                        const fieldsArray = therapist.fields
                            .split(',')
                            .filter(field => field.trim() !== '');

                        return {
                            id: therapist.id,
                            name: therapist.name,
                            phone: therapist.phone,
                            title: therapist.title,
                            avatar: therapist.avatar || this.getDefaultAvatar(therapist.gender),
                            gender: therapist.gender,
                            qualification: therapist.qualification,
                            experience: therapist.experience,
                            fields: fieldsArray,
                            bio: therapist.bio,
                            rating: therapist.rating || 5.0,
                            consultations: therapist.consultations || 0
                        };
                    });
                    console.log('处理后的数据:', this.therapists);
                    this.loading = false;
                } else if (data.code === "401") {
                    console.log('Token验证失败');
                    localStorage.removeItem('token');
                    window.location.href = '/login.html';
                } else {
                    throw new Error(data.message || '获取咨询师列表失败');
                }
            } catch (error) {
                console.error('获取咨询师列表失败:', error);
                if (error.response?.status === 401) {
                    localStorage.removeItem('token');
                    window.location.href = '/login.html';
                } else {
                    this.error = '获取咨询师列表失败，请稍后重试';
                }
            } finally {
                this.loading = false; // 确保在任何情况下都设置loading为false
            }
        },
        getDefaultAvatar(gender) {
            return gender === '女' ? 'images/therapist-female.svg' : 'images/therapist-male.svg';
        },
        openAppointmentForm(therapist) {
            this.selectedTherapist = therapist;
            this.showAppointmentForm = true;
            this.generateAvailableDates();
        },
        generateAvailableDates() {
            // Implementation of generateAvailableDates method
        },
        closeDetail() {
            this.showDetailModal = false;
            this.selectedTherapist = null;
        },
        makeAppointmentFromDetail() {
            this.showDetailModal = false;
            this.makeAppointment(this.selectedTherapist);
        },
        checkExperienceMatch(experience, filter) {
            const years = parseInt(experience);
            switch (filter) {
                case '0-3':
                    return years < 3;
                case '3-5':
                    return years >= 3 && years < 5;
                case '5-10':
                    return years >= 5 && years < 10;
                case '10+':
                    return years >= 10;
                default:
                    return true;
            }
        },
        async handleDateChange() {
            if (this.selectedDate && this.selectedTherapist) {
                this.selectedTime = '';
                await this.fetchAvailableTimeSlots(this.selectedTherapist.phone, this.selectedDate);
            }
        },
        async fetchAvailableTimeSlots(therapistPhone, date) {
            try {
                const token = localStorage.getItem('token');
                const response = await fetch(`/api/appointments/available-time?therapistPhone=${therapistPhone}&date=${date}`, {
                    headers: {
                        'Authorization': token
                    }
                });

                if (response.status === 401) {
                    localStorage.removeItem('token');
                    window.location.href = '/login.html';
                    return;
                }

                const data = await response.json();
                if (data.code === "200") {
                    this.availableTimeSlots = data.data;
                } else {
                    throw new Error(data.message || '获取可预约时间失败');
                }
            } catch (error) {
                console.error('获取可预约时间失败:', error);
                this.availableTimeSlots = [];
                alert('获取可预约时间失败，请稍后重试');
            }
        }
    },
    created() {
        this.fetchTherapists();
    }
}).mount('#app'); 